<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	 <link rel="stylesheet" href="layui/css/layui.css"  media="all">
	 <link href='humane/libnotify.css' rel='stylesheet'>
	<style>
		body{
			margin: 0;
		}
		#container{
			min-width: 1280px;
			display: flex;
		}
		#left{
			flex: 1;
			/*background: red;*/
		}
		#main{
			flex: 3;
			/*background: green;*/
		}
		#right{
			flex: 1;
			/*background: blue;*/
		}
		/*@media screen and (max-width: 1200px){
			#main{
				flex: 2;
			}
		}*/
		/*涨跌的颜色*/
		.up-label{
			color: #FF5722;
		}
		.down-label{
			color: #5FB878;
		}
		/*标签页主题色*/
		#leftTab .layui-tab-title li,#digramTab .layui-tab-title li{
			color: #999;
		}
		#leftTab>.layui-tab-title .layui-this{
			color: #2F4056;
		}
		#leftTab>.layui-tab-title .layui-this:after{
			border-bottom: 2px solid #2F4056;
		}

		/*左边的部件*/
		#searchArea{
			display: flex;
			transition: none;
			-webkit-transition: none;
		}
		#searchIcon{
			margin-top: 6px;
			margin-right: 8px;
		}
		#keyword{
			height: 36px;
			border:none; 
			line-height: 36px; 
			flex: 1
		}
		#clearBtn{
			width: 32px; 
			background: transparent; 
			border: none; 
			cursor: pointer;
		}
		.searchDisabled{
			background: #eee;
		}
		/*不让翻页按钮左右乱跑*/
		#left .layui-laypage-stocklist{
			display: flex;
		}
		#left .layui-laypage-stocklist span,a {
			flex: 1;
			text-align: center;
		}
		/*更改分页器的选中颜色*/
		#left .layui-laypage-stocklist .layui-laypage-curr .layui-laypage-em{
			background-color: #2F4056;
		}
		/*去除表格点击的灰色背景*/
		.layui-table-click{
			background: none;
		}
		
		
		/*中间部分*/
		/*标签页部分*/
		.main-tabbar{
			margin: 10px 0;
			border-bottom: 1px solid #e6e6e6;
			/*overflow-x: scroll;*/
			/*display: flex;*/
			height: 40px;
			overflow: hidden;
			background: #f2f2f2;
		}
		.main-tabbar .main-tabbar-tab{
			height: 39px;
			max-width: 120px;
			/*min-width: 60px;*/
			/*flex: 1;*/
			/*line-height: 40px;*/
			padding: 4px 8px;
			font-size: 14px;
			display: flex;
			/*flex-direction: row;*/
			cursor: pointer;
			display: inline-flex;
			/*vertical-align: middle;*/
			/*border-right: 1px solid #ccc;*/
			box-sizing: border-box;
			/*border-bottom: 1px solid #e6e6e6;*/
		}
		.main-tabbar .main-tabbar-tab .main-tabbar-title{
			flex: 1;
			font-size: 12px;
			/*line-height: 20px;*/
			/*display: inline-block;*/
			/*padding-top: 4px;*/
			/*padding-bottom: 4px;*/
			text-align: center;
		}
		/*.main-tabbar li .main-tabbar-title div{

		}*/
		.main-tabbar .main-tabbar-tab .main-tabbar-close{
			margin-left: 8px;
			/*display: inline-block;*/
			/*margin-top: -4px;*/
			/*flex: 1*/
			/*height: 30px;*/
			line-height: 30px;
		}
		.main-tabbar .main-tabbar-tab .main-tabbar-close:hover{
			color: #FF5722;
		}
		/*选中*/
		.main-tabbar .main-tabbar-select{
			border: 1px solid #ccc;
			border-bottom: none;
			box-sizing: border-box;
			background: #fff;
			/*margin-top: -1px;*/
		}
		.main-tabbar .main-tabbar-tab:not(.main-tabbar-select):hover{
			background: #fcfcfc;
			transition: all .3s;
			-webkit-transition: all .3s;
		}


		/*头部*/
		.main-row{
			display: flex;
			color: #666;
		}
		.main-head-left{
			padding: 0 15px;
			text-align: center;
		}
		#mainPriceRow{
			display: flex;
			height: 40px;
		}
		#mainPrice{
			font-size: 32px;
		}
		#mainUpdown{
			font-size: 32px;
		}
		/*#mainUpdownPrice,#mainUpdownPercent{
			line-height: 20px;
		}*/
		.main-head-right{
			flex: 1;
			text-align: center;
		}
		.main-head-right p{
			line-height: 20px;
			min-width: 86.5px;
		}

		/*图表标签*/
		#digramTab .layui-tab-title{
			height: 20px;
		}
		#digramTab .layui-tab-title li{
			line-height: 20px;
		}
		#digramTab .layui-tab-title .layui-this:after{
			height: 21px;
		}
		#digramTab>.layui-tab-title .layui-this{
			color: #2F4056;
		}
		#digramTab>.layui-tab-title .layui-this:after {
			border-bottom: 2px solid #2F4056;
		}

		.main-foot-col{
			flex: 1;
		}
		.main-foot-col:first-child .main-foot-col{
			text-align: center;
		}
		.main-foot-col:first-child p{
			line-height: 30px;
		}

		
		/*.button-des-text{
			font-size: 12px;
			text-align: center;
		}*/

		#buySellTab{
			margin: 0;
		}
		#buySellTab .layui-tab-title{
			height: 20px;
		}
		#buySellTab .layui-tab-title li{
			line-height: 20px;
		}
		#buySellTab .layui-tab-title .layui-this:after{
			height: 21px;
		}
		#buySellTab>.layui-tab-title .layui-this{
			color: #2F4056;
		}
		#buySellTab>.layui-tab-title .layui-this:after {
			border-bottom: 2px solid #2F4056;
		}
		.buySellValueControll{
			/*display: flex;*/
			padding: 0 16px;
		}
		.buySellValueControll button{
			width: 20px;
			padding: 0 2px;
		}
		.amount-input{
			border:0;
			width:70px;
			height:25px;
			text-align:center;
			/*flex: 1*/
		}
		#buySellVolBtnGroup{
			margin-top: 5px;
			margin-left: 16px;
		}
		#buySellVolBtnGroup button{
			padding: 0 4px;
		}
		.buyButton:hover{
			border-color: #FF5722;
			color: #FF5722;
		}
		.sellButton:hover{
			border-color: #01AAED;
			color: #01AAED;
		}
		#buySellSubmit{
			margin-top: 8px;
		}

		#right{
			padding: 16px;
			/*max-width: 256px;*/
		}
		#userTab .layui-tab-content{
			padding: 8px 0;
		}
		#userTab .layui-tab-title li,#userTab .layui-tab-title li{
			color: #999;
		}
		#userTab>.layui-tab-title .layui-this{
			color: #2F4056;
		}
		#userTab>.layui-tab-title .layui-this:after{
			border-bottom: 2px solid #2F4056;
		}
		#userDataContainer{
			overflow: auto;
			/*overflow: auto;*/
			padding: 0 16px;
		}
		.holdingRow{
			display: flex;
			/*padding: 4px 0;*/
			border-bottom: 1px solid #dfdfdf;
			color: #666;
			transition: all .3s;
			-webkit-transition: all .3s;
			padding: 2px;
			cursor: pointer;
		}
		.holdingRow:hover{
			background: #f2f2f2;
		}
		.holdingCol{	
			flex: 1;
			line-height: 20px;
		}
		.delegateRow{
			border-bottom: 1px solid #dfdfdf;
			color: #666;
			transition: all .3s;
			-webkit-transition: all .3s;
			padding: 2px;
		}
		.delegateInfoRow{
			display: flex;
			line-height: 20px;
		}
		.delegateCol{
			flex: 1;
		}
		.delegateStock:hover{
			text-decoration: underline;
			cursor: pointer;
			color: #999;
		}

	</style>
</head>
<body>
<div id="container" class="layui-row">
	<div id="left">
		<div class="layui-tab layui-tab-brief" lay-filter="leftTab" id="leftTab">
			<ul class="layui-tab-title">
				<li class="layui-this">股票列表</li>
				<!-- <li>涨跌榜</li> -->
				<li>自选股</li>
			</ul>
			<div class="layui-tab-content">
				<!-- <div class="layui-tab-item layui-show"> -->
				<div class="layui-input" id="searchArea">
					<span id="searchIcon" class="layui-icon">&#xe615;</span>
					<input type="text" name="keyword" placeholder="名称、代码、拼音" autocomplete="off" id="keyword" >
					<button id="clearBtn"><i class="layui-icon">&#x1006;</i></button>
				</div>
				<table id="stockTable" lay-filter="stock"></table>
				<!-- </div> -->
			    <!-- <div class="layui-tab-item">敬请期待</div> -->
			    <!-- <div class="layui-tab-item">
					<div id="stockUnloginedLabel">请先登录</div>
					<div id="stockSelectedList"></div>
				</div> -->
				<div id="selectedStockPager"></div>
			</div>
		</div> 
	</div>
	<div id="main">
		<div class="main-tabview">
			<div class="main-tabbar" id="mainTabbar">
				<!-- <div class="main-tabbar-tab main-tabbar-select">
					<div class="main-tabbar-title">
						浦发银行<br>
						600000
					</div>
					<div class="layui-icon main-tabbar-close">&#x1006;</div>
				</div> -->
			</div>
			<!-- layui模板 -->
			<script type="text/html" id="mainTabTpl">
				{{# layui.each(d, function(index, item){ }}
				<div class="main-tabbar-tab">
					<div class="main-tabbar-title">
						{{item.name}}
						<br>
						{{item.id}}
					</div>
					<div class="layui-icon main-tabbar-close">&#x1006;</div>
				</div>
				{{# }) }}
			</script>
			<div class="tab-content" style="display: none;">
				<!-- 头部信息 -->
				<div class="main-row">
					<div class="main-head-left">
						<div>
							<!-- 添加到自选股按钮 -->
							<button class="layui-btn layui-btn-sm layui-btn-primary" id="addBtn" class="addBtn">
								<i class="layui-icon" id="addBtnIcon">&#xe600;</i> 
								<span id="addBtnLabel">------ (------)</span>
							</button>
						</div>
						<div id="mainPriceRow">
							<div id="mainPrice"></div>
							<div id="mainUpdown"></div>
							<div style="padding: 4px 0">
								<div id="mainUpdownPrice"></div>
								<div id="mainUpdownPercent"></div>
							</div>
						</div>
						
						<div id="mainTime"></div>
						
					</div>
					<div class="main-head-right">
						<p>今开</p>
						<p>最高</p>
						<p>最低</p>
						<p>昨收</p>
					</div>
					<div class="main-head-right">
						<p id="mainOpen">--</p>
						<p id="mainMax">--</p>
						<p id="mainMin">--</p>
						<p id="mainClose">--</p>
					</div>
					<div class="main-head-right">
						<p>成交量</p>
						<p>成交额</p>
						<p>涨停</p>
						<p>跌停</p>
					</div>
					<div class="main-head-right">
						<p id="mainVol">--</p>
						<p id="mainTotal">--</p>
						<p id="mainMaxStop">--</p>
						<p id="mainMinStop">--</p>
					</div>
				</div>
				<!-- 图表 -->
				<div class="layui-tab layui-tab-brief" lay-filter="digramTab" id="digramTab">
					<ul class="layui-tab-title" id="digramTabbar">
						<li class="layui-this" lay-id="timeline">分时</li>
						<li lay-id="dayK">日K</li>
						<li lay-id="weekK">周K</li>
						<!-- <li lay-id="monthK">月K</li> -->
					</ul>
					<div class="layui-tab-content">
						<!-- baidu echarts -->
						<div id="echartsInstance" style="height: 300px;"></div>
					</div>
				</div>
				<!-- 买卖 -->
				<div class="main-row">
					<div class="main-foot-col" style="display: flex;">
						<div class="main-foot-col">
							<p>卖5</p>
							<p>卖4</p>
							<p>卖3</p>
							<p>卖2</p>
							<p>卖1</p>
						</div>
						<div class="main-foot-col" id="sellPrice">
							<p>--</p>
							<p>--</p>
							<p>--</p>
							<p>--</p>
							<p>--</p>
						</div>
						<div class="main-foot-col" id="sellVol">
							<p>--</p>
							<p>--</p>
							<p>--</p>
							<p>--</p>
							<p>--</p>
						</div>
						<div class="main-foot-col">
							<p>买1</p>
							<p>买2</p>
							<p>买3</p>
							<p>买4</p>
							<p>买5</p>
						</div>
						<div class="main-foot-col" id="buyPrice">
							<p>--</p>
							<p>--</p>
							<p>--</p>
							<p>--</p>
							<p>--</p>
						</div>
						<div class="main-foot-col" id="buyVol">
							<p>--</p>
							<p>--</p>
							<p>--</p>
							<p>--</p>
							<p>--</p>
						</div>
					</div>
					<div class="main-foot-col">             
                        <!-- <div class="main-foot-col">  -->
                        	<!-- style="padding: 0 16px" -->
                		<div class="layui-tab layui-tab-brief" id="buySellTab" lay-filter="buySellTab">
                            <ul class="layui-tab-title">
                                <li class="layui-this" lay-id="buy">买入</li>
                                <li lay-id="sell">卖出</li>
                            </ul>
                            <div class="layui-tab-content">
                                <!-- <div class="layui-tab-item layui-show">   -->
                                <div  style="display: flex;">
	                                <div class="main-foot-col">
										<div class="buySellValueControll">
				                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="buySellPriceReduce">
				                                <i class="layui-icon">&#xe603;</i>
				                            </button>
				                            <input type="text" class="amount-input" value="0.00" id="buySellPriceInput" />
				                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="buySellPriceAdd">
				                                <i class="layui-icon">&#xe602;</i>
				                            </button>
				                        </div>
				                        <div style="margin-top: 10px" class="buySellValueControll">
				                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="buySellVolReduce">
				                                <i class="layui-icon">&#xe603;</i>
				                            </button>
				                            <input type="text" class="amount-input" value="0" id="buySellVolInput" />
				                            <button class="layui-btn layui-btn-primary layui-btn-sm" id="buySellVolAdd">
				                                <i class="layui-icon">&#xe602;</i>
				                            </button>
				                        </div>
				                        <div class="layui-btn-group" id="buySellVolBtnGroup">
				                            <button class="layui-btn layui-btn-primary layui-btn-sm">全仓</button>
				                            <button class="layui-btn layui-btn-primary layui-btn-sm">半仓</button>
				                            <button class="layui-btn layui-btn-primary layui-btn-sm">1/3</button>
				                            <button class="layui-btn layui-btn-primary layui-btn-sm">1/4</button>
				                        </div>
									</div>
									<div class="main-foot-col">
										<p>合计: <span id="buySellTotal">0.00</span></p>
	                                    <p>仓位: <span id="buySellHolding">--</span>%</p>
	                                    <p>可<span class="buySellLabel">买</span>: <span id="buySellAvailable">--</span></p>
	                                    <button class="layui-btn layui-btn-sm layui-btn-primary layui-btn-fluid buyButton" id="buySellSubmit">买入</button>
									</div>
                                </div>
                                <!-- </div> -->

                            </div>
                        </div>
						<!-- </div> -->
					</div>
					
				</div>
			</div>
		</div>
		
	</div>
	<div id="right">
		<div id="body-login" >
				<!-- style="display: none" -->
	        <div id="title-login" style="margin-top:50px;text-align:center;font-size: 24px">登入模拟交易系统</div>
	        <div id="title-regist" style="margin-top:50px;text-align:center;display:none;font-size: 24px">注册账号</div>
	        <hr>
	        <form class="layui-form layui-form-pane" >                        
	            <input type="text" id="user" autocomplete="off" placeholder="请输入用户名" class="layui-input">  
	            <div id="regist-message" style="color:red;size:2"></div>                  
	            <input type="password" id="password" autocomplete="off" placeholder="请输入密码" class="layui-input" style="margin-top:15px">
	            <input type="password" id="confirm-password" autocomplete="off" placeholder="再次输入密码" class="layui-input" style="display:none;margin-top:15px">
	            <div style="margin-left:30px;margin-top:15px" id="login-Btn">
	                <button class="layui-btn" id="loginBtn" lay-submit lay-filter="loginForm" >登录</button>
	                <button class="layui-btn layui-btn-primary" id="toLoginBtn" lay-submit lay-filter="loginForm" >去注册</button>
	            </div>
	            <div id="login-message" style="color:red;size:2"></div> 
	        </form> 
	    </div>          
	    <div id="body-user"  style="display:none">
	    	<div id="user-info">
		        <div style="padding: 8px;display: flex;"> <!-- style="height:60px" -->
		            <!-- <div> -->
		            <img src="http://t.cn/RCzsdCq" class="layui-nav-img" style="width:50px;height:50px">
		            <!-- </div> -->
		            <!-- <div> -->
	                <!-- <div> -->
	                <div style="margin-top: 10px; flex: 1" id="user-name">User1</div>
	                <!-- </div> -->
	                <!-- <div> -->
	                <button class="layui-btn layui-btn-primary" style="margin-top:10px" id="logoutBtn" lay-submit lay-filter="formDemo" >注销</button>
	                <!-- </div> -->
		            <!-- </div> -->
		            <!-- <br> -->
		        </div>
		        <hr>
		        <div style="display: flex; padding: 0px 16px;">    <!-- style="height:125px" -->
		        	<div style="flex: 1; line-height: 30px;">
		        		<p><i class="layui-icon">&#xe65e;</i> 总资产</p>
		        		<p><i class="layui-icon">&#xe62c;</i> 浮动盈亏</p>
		        		<p><i class="layui-icon">&#xe60b;</i> 总市值</p>
		        		<p><i class="layui-icon">&#xe629;</i> 仓位</p>
		        	</div>
		        	<div style="flex: 1; line-height: 31.5px;text-align: right;">
		        		<p id="userRemainTotal">0.00</p>
		        		<p id="userUpdown">0.00</p>
		        		<p id="userHoldingTotal">0.00</p>
		        		<p><span id="userVolume"></span>%</p>
		        	</div>
		            
		        </div>
	    	</div>
	        <!-- <div> -->
	            <div class="layui-tab layui-tab-brief" lay-filter="userTab" id="userTab">
	                <ul class="layui-tab-title">
		                <li class="layui-this" lay-id="holding">持仓</li>
		                <li lay-id="delegate">委托</li>
		                <li lay-id="deal">成交</li>
	                </ul>
	                <div class="layui-tab-content">
						<script type="text/html" id="holdingTpl">
							{{# layui.each(d, function(index, item){ }}
							<div class="holdingRow">
								<div class="holdingCol">
									<p><span class="holdingRowName">{{item.name}}</span>(<span class="holdingRowStockid">{{item.stock_id}}</span>)</p>
									<p class="{{item.updownClass}}">{{item.buyPrice}} {{item.updown}} {{item.nowPrice}}</p>
								</div>
								<div class="holdingCol" style="text-align: right;">
									<p>{{item.available}}/{{item.amount}}({{item.volume}}%)</p>
									<p class="{{item.updownClass}}">{{item.updownPrice}}({{item.updownRate}}%)</p>
								</div>
							</div>
							{{# }) }}
						</script>
						
						<script type="text/html" id="delegateTpl">
							{{# layui.each(d, function(index, item){ }}
							<div class="delegateRow">
								<div class="delegateInfoRow">
									<div class="delegateCol delegateStock"><span class="delegateRowName">{{item.name}}</span>(<span class="delegateRowStockid">{{item.stockId.replace('sh','')}}</span>)</div>
									<div class="delegateCol" style="text-align: right"><i class="layui-icon">&#xe65e;</i> {{item.price.toFixed(2)}}</div>
								</div>
								<div class="delegateInfoRow">
									<div class="layui-badge layui-bg-{{item.type ? 'orange':'blue'}}">{{item.type ? '买入':'卖出'}}</div>
									<div class="delegateCol" style="text-align: right;padding: 0 8px;">{{item.num}}</div>
									<div class="layui-badge layui-bg-green">成交</div>
									<div class="delegateCol" style="text-align: right;padding: 0 8px;">{{item.deal}}</div>
								</div>
								<div class="delegateInfoRow">
									<div class="delegateCol">{{item.time}}</div>
									<button class="delegateCancel layui-btn layui-btn-{{item.deal<item.num ? 'danger':'disabled'}} layui-btn-xs">取消</button>
								</div>
							</div>
							{{# }) }}
						</script>

						<script type="text/html" id="dealTpl">
							{{# layui.each(d, function(index, item){ }}
							<div class="delegateRow">
								<div class="delegateInfoRow">
									<div class="delegateCol delegateStock"><span class="delegateRowName">{{item.name}}</span>(<span class="delegateRowStockid">{{item.stockId.replace('sh','')}}</span>)</div>
								</div>
								<div class="delegateInfoRow">
									<div class="layui-badge layui-bg-{{item.type ? 'orange':'blue'}}">{{item.type ? '买入':'卖出'}}</div>
									<div class="delegateCol" style="text-align: right;padding: 0 8px;">{{item.num}}</div>
									<i class="layui-icon">&#xe65e;</i>
									<div class="delegateCol" style="text-align: right;padding: 0 8px;">{{item.price.toFixed(2)}}</div>
								</div>
								<div class="delegateInfoRow">
									<div class="delegateCol">{{simpleDateFormat(item.time)}}</div>
								</div>
							</div>
							{{# }) }}
						</script>

						<div id="userDataContainer">
								
						</div>
						<!-- <div class="layui-tab-item layui-show"> -->
							<!-- <div id="userDataContainer"> -->
								<!-- <div class="holdingRow">
									<div class="holdingCol">
										<p>浦发银行(600000)</p>
										<p>11.66 ▲ 11.73</p>
									</div>
									<div class="holdingCol" style="text-align: right;">
										<p>0/100(0.6%)</p>
										<p>+6.74(+0.576%)</p>
									</div>
								</div> -->
							<!-- </div> -->
						<!-- </div> -->
						<!-- <div class="layui-tab-item"> -->
							<!-- <div id="userDelegateList"></div> -->
						<!-- </div> -->
						<!-- <div class="layui-tab-item"> -->
							<!-- <div id="userDealList"></div> -->
						<!-- </div> -->
	                	
	                </div>
	            </div>
	        <!-- </div> -->
	    </div>
	</div>
</div>

<!-- layui的js文件 -->
<script src="layui/layui.js"></script>
<!-- jquery -->
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- jquery-ui -->
<script src="http://apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<!-- 股票列表，静态文件 -->
<script src="stocks.js"></script>
<!-- taffy用于json数据的query查询，实现关键词搜索 -->
<script src="taffy.js"></script>
<!-- 百度echarts画图表 -->
<script src="echarts.min.js"></script>
<!-- humane消息弹出插件 -->
<script src="humane/humane.min.js"></script>

<!-- 测试用的数据 -->
<!-- <script src="day.js"></script> -->

<!-- 放置sinajs -->
<span id="sinaScript"></span>
<span id="selectedCode"></span>
<span id="holdingScript"></span>

<script>

var App = {
	searching: false, // 是否在搜索状态
	stockTableLimit: 0, // 以表格的高度计算每页条数 初始化时决定
	stockTableCurr: 0, // 表格当前的页面
	stockCodesInPage: [], // 表格当前页面中股票的代码
	getPriceTimerReady: false, // 表格是否完成数据加载(计时器是否可以掺一脚)
	selectedStock: '', // 中间部分选中的股票代码
	// selectedIndex: [null, 0],
	selectingStock: [], // 中间部分标签栏打开的股票
	nowMinute: 0, // 计时器用于判断是否已过一分钟
	digramTabIndex: 0, // 图表区域选中的标签index
	loginRegState: 0, // 登陆界面与注册界面的切换状态
	userLogined: false, // 用户是否登陆
	holding: {}, // 用户持仓
	userDefaultRemain: 200000, // 用户默认的余额
	userDelegate: [], // 用户委托
}

var stockDb = TAFFY(StockList)

var simpleDateFormat = function(timestamp){
	var date = new Date()
	date.setTime(timestamp)
	return date.getFullYear()+'-'+(date.getMonth()<9?'0':'')+(date.getMonth()+1)+'-'+(date.getDate()<10?'0':'')+date.getDate()
		+' '+ (date.getHours()<10?'0':'')+date.getHours() +':'+ (date.getMinutes()<10?'0':'')+date.getMinutes() +':'+ (date.getSeconds()<10?'0':'')+date.getSeconds()
}


// $(document).tooltip()

layui.use(['element','jquery', 'layer', 'table', 'laytpl', 'laypage'], function(){
	var $ = layui.$ //jquery
	,layer = layui.layer;

	
	// 左边的部件的代码

	// 新浪接口
	var sinaScript = document.getElementById('sinaScript')
	
	var table = layui.table;
	var element = layui.element
	var laypage = layui.laypage

	// 表格
	table.render({
		elem: '#stockTable',
		height: 'full-120',
		skin: 'nob',
		size: 'sm',
		data: StockList, //股票列表
		page: {
			groups: 2,
			layout: ['prev','page', 'next'],
			theme: 'stocklist'
		},
		limit: 20,
		cols: [[ //表头
		  {field: 'id', title: '代码', event: 'detail', style:'cursor: pointer;'}, // 每一列都有点击事件
		  {field: 'name', title: '名称', minWidth: 80, event: 'detail', style:'cursor: pointer;'},
		  {field: 'price', title: '价格', event: 'detail', style:'cursor: pointer;'}
		]],
		done: function(res, curr, count){
			// console.log(res)
			
			if (App.stockTableLimit != 0 && !App.searching && App.stockTableCurr != curr) {
				// 已完成每页条数的计算 && 不在搜索中 && 刚刚换页
				App.getPriceTimerReady = false
				App.stockCodesInPage = res.data.map(function(x){return 'sh' + x.id})
				var idx = $("#leftTab .layui-tab-title .layui-this").index()
				if (idx == 0) App.stockTableCurr = curr
				// console.log(curr)
				// 开始刷新
				sinaScript.innerHTML = ''
				var scriptElem = document.createElement("script")
				scriptElem.src = "http://hq.sinajs.cn/list=" + App.stockCodesInPage.join(',')
				sinaScript.appendChild(scriptElem)
				scriptElem.onload = function(){
					if (idx == 0){
						for (var i = (curr-1)*App.stockTableLimit; i < curr*App.stockTableLimit; i++) {
							if (StockList[i] === undefined) break
							//&#xe61a; &#xe619;
							var digits = eval("hq_str_sh" + StockList[i].id).split(',')
							// var icon = digits[3]>digits[1]?'&#xe619;':digits[3]<digits[1]?'&#xe61a;':'丨'
							var price = parseFloat(digits[3])
							var open = parseFloat(digits[1])
							// 涨跌的颜色class
							var updown = open == 0 ? '' : price>open?'up-label':price<open?'down-label':''
							// 涨跌图标
							var icon = open == 0 ? '--' : price>open?'▲':price<open?'▼':'--'
							// 合成一个价格涨跌span
							var priceSpan = '<span class="price-label '+updown+'">' + icon+'&nbsp;'+ (price < 10 ? '&nbsp;&nbsp;' : '') + price.toFixed(2) + '</span>'
							StockList[i].price = priceSpan
						}
						table.reload('stockTable', {
							data: StockList
						})
					}
					else if (idx == 1){
					// 	if (App.stockTableCurr != 0) {
							// $.get('stock/selected?page='+curr+'&limit='+App.stockTableLimit, function(result){
							// 	if (result.status === -1){
							// 		loginInvaildated()
							// 		return
							// 	}
							// 	if (result.status === 200){
							// 		App.stockTableCurr = 0
							// 		table.reload("stockTable", {
							// 			page: {
							// 				count: result.count,
							// 				limit: App.stockTableLimit											
							// 			},
							// 			data: result.data.map(function(x){
							// 				return {id: x.replace('sh',''), name: stockDb({id: x.replace('sh', '')}).first().name}
							// 			})
							// 		})
							// 	}
							// })
					// 	}else{
							for (var i=0; i < res.count; i++){
								//&#xe61a; &#xe619;
								var digits = eval("hq_str_sh" + res.data[i].id).split(',')
								// var icon = digits[3]>digits[1]?'&#xe619;':digits[3]<digits[1]?'&#xe61a;':'丨'
								var price = parseFloat(digits[3])
								var open = parseFloat(digits[1])
								// 涨跌的颜色class
								var updown = open == 0 ? '' : price>open?'up-label':price<open?'down-label':''
								// 涨跌图标
								var icon = open == 0 ? '--' : price>open?'▲':price<open?'▼':'--'
								// 合成一个价格涨跌span
								var priceSpan = '<span class="price-label '+updown+'">' + icon+'&nbsp;'+ (price < 10 ? '&nbsp;&nbsp;' : '') + price.toFixed(2) + '</span>'
								res.data[i].price = priceSpan
							}
							App.stockTableCurr = curr
							table.reload('stockTable', {
								data: res.data
							})
							
					// 	}
						
					}
					
					App.getPriceTimerReady = true

				}
				// console.log(App.stockTablePage)
			}

			// if (App.selectedIndex[1] == curr && App.selectedIndex[0] != null) {
			// 	$(App.selectedIndex[0]).siblings().css({'background': '', 'color': ''}) 
			// 	$(App.selectedIndex[0]).css({'background': '#2F4056', 'color': 'white'})
			// }
		}
	});

	// 页面高度
	App.stockTableLimit = Math.floor($("#left .layui-table-body").height() / 30)
	table.reload("stockTable", { // relaod时会触发table的done回调
		page:{
			limit: App.stockTableLimit
		}
	})

	// 左边标签栏切换事件
	element.on('tab(leftTab)', function(data){
		if (data.index == 0){
			// $("#keyword").removeAttr('disabled')
			// $("#searchArea").removeClass("searchDisabled")
			// $("#keyword").removeClass('searchDisabled')
			$("#searchArea").show()
			$("#selectedStockPager").hide()
			// $(".layui-laypage-stocklist").show()
			App.stockTableCurr = 0
			table.reload("stockTable", {
				data: StockList,
				text: {
					none: '无数据'
				},
				page: {
					limit: App.stockTableLimit,
					curr: 1,
					groups: 2,
					layout: ['prev','page', 'next'],
					theme: 'stocklist'
				},
				height: 'full-120',
			})
		}else if (data.index == 1){
			$("#keyword").val('') // 清空关键词
			// $("#keyword").attr('disabled', 'disabled')
			App.searching = false
			// $("#searchArea").addClass("searchDisabled")
			// $("#keyword").addClass('searchDisabled')	
			// $(".layui-laypage-stocklist").hide()
			$('#searchArea').hide()
			if (App.userLogined) {
				refreshSelectedStock()
			}else{
				table.reload("stockTable", {
					data: [],
					text: {
						none: '请先登录'
					}
				})
			}
			
		}
		
	})

	// 刷新自选股表格
	var refreshSelectedStock = function(){
		// App.stockTableCurr = 0
		$.get('stock/selected?page=1&limit='+App.stockTableLimit, function(result){
			// console.log(result)
			if (result.status === -1){
				loginInvaildated()
				table.reload("stockTable", {
					data: [],
					text: {
						none: '请先登录'
					}
				})
				return
			}
			if (result.status === 200){
				App.stockTableCurr = 0
				table.reload("stockTable", {
					height: 'full-160',
					text: {
						none: '无数据'
					},
					page: false,//{
					// 	curr: 1,
					// 	count: result.count,
					// 	limit: App.stockTableLimit
					// },
					data: result.data.map(function(x){
						return {id: x.replace('sh',''), name: stockDb({id: x.replace('sh', '')}).first().name}
					})
				})
				$("#selectedStockPager").show()
				laypage.render({
					elem: 'selectedStockPager',
					count: result.count,
					limit: App.stockTableLimit,
					groups: 2,
					layout: ['prev','page', 'next'],
					theme: 'stocklist',
					prev: '<i class="layui-icon">&#xe603;</i>',
					next: '<i class="layui-icon">&#xe602;</i>',
					jump: function(obj, first){
						console.log(obj.curr)
						$.get('stock/selected?page='+obj.curr+'&limit='+App.stockTableLimit, function(result){
							if (result.status === -1){
								loginInvaildated()
								return
							}
							if (result.status === 200){
								App.stockTableCurr = 0
								table.reload("stockTable", {
									data: result.data.map(function(x){
										return {id: x.replace('sh',''), name: stockDb({id: x.replace('sh', '')}).first().name}
									})
								})
							}
						})
					}
				})
			}else{
				table.reload("stockTable", {
					data: [],
					text: {
						none: '系统出错，GG'
					}
				})
			}
		})
	}

	$("#keyword").on('input', function(e){ // 绑定输入框事件
		var keyword = $("#keyword").val() // 获取输入的关键词
		if (keyword.length > 0) {
			App.searching = true
			// 开始搜索
			stockDb = TAFFY(StockList)
			var query1 = stockDb({id: {likenocase: keyword}}) // likenocase 忽略大小写
			var query2 = stockDb({name: {likenocase: keyword}}) // 名字查询
			var query3 = stockDb({py: {likenocase: keyword}})  // 拼音查询
			var query4 = stockDb({pinyin: {likenocase: keyword}}) // 拼音首字母查询
			query = query1.get().concat(query2.get(), query3.get(), query4.get())
			table.reload('stockTable', {
				data: query, // 更新表格数据
				page: {
					curr: 1
				}
			});
		}else{ // 关键词为空的时候回复原来的数据
			App.searching = false
			table.reload('stockTable', {
				data: StockList,
				page: {
					curr: App.stockTableCurr
				}
			});
		}
		
	})

	// 搜索框清除关键词
	$("#clearBtn").click(function(){
		if ($("#keyword").val() != '') {
			$("#keyword").val('') // 清空关键词
			App.searching = false
			table.reload('stockTable', {
				data: StockList, // 回到初始的股票列表
				page: {
					curr: App.stockTableCurr
				}
			});
		}
		
	})

	// 中间
	
	// 分时线图表
	var refreshTimeline = function(day, callback, errorHandler){
		if(App.selectedStock != ''){
			// console.log(day)

			$.get('/stock/quoteK/sh'+App.selectedStock+'/'+day, function(data){
				// console.log(data)
				if (Array.isArray(data.data) && data.data.length != 0) {
					App.nowMinute = (new Date()).getMinutes()

					var StocksPrice = data.data
					var nowTime = [] //当前时间
    
				    var averagePrice = [] //平均价位
				    var nowPrice = [] //当前价位
				    var nowVol = []
				    var upVol = [] //涨成交量
				    var priceMax = 0 
				    var priceMin = 0

				    for (var i = 0; i < 242; i++) {
				        var ampm = Math.floor(i/121)
				        var minute = i + 30 - ampm*151
				        var hour = 9 + ampm*4
				        while(minute >= 60){
				            minute -= 60
				            hour ++
				        }
				        // console.log(hour)
				        nowTime[i] = hour + ":" + (minute < 10 ? "0":"") + minute
				        
				    }
				    // console.log(nowTime)
				    for(var i = 0 ; i < StocksPrice.length ; i++){

				        var timeCompo = StocksPrice[i].time.split(":")

				        var hour = parseInt(timeCompo[0])
				        var min = parseInt(timeCompo[1])
				        var sec = parseInt(timeCompo[2])
				        if (sec > 30) min += 1
				        if (min >= 60) {
				            min = 0
				            hour += 1
				        }

				        var x = -1;
				        if (hour == 9 && min >= 30) x = min - 30
				        else if (hour == 10) x = min + 30
				        else if (hour == 11) x = min + 90
				        else if (hour >= 13 && hour <= 15) {
				            x = (hour-13)*60 + min + 121
				        }

				        if (x == -1) continue
				        // console.log(x + ":" + i + " " + hour + ":" + min)
				        var price = parseFloat(StocksPrice[i].price)
				        
				        var avg = parseFloat(StocksPrice[i].total / StocksPrice[i].volume).toFixed(3)
				        var maxmax = avg > price ? avg : price
				        if (maxmax > priceMax) {
				        	priceMax = maxmax
				        }
				        var minmin = avg < price ? avg : price
				        if (priceMin == 0) {
				        	priceMin = minmin
				        }else if (minmin < priceMin) {
				        	priceMin = minmin
				        }
				        // console.log(i+","+x)
				        price = price.toFixed(2)
				        var lastIndex = nowPrice.length-1

				        if (lastIndex >= 0) {
				            if (nowPrice[lastIndex][0] == x) {
				                var last = nowPrice.length-1
				                averagePrice[lastIndex][1] = avg
				                nowPrice[lastIndex][1] = price
				                nowVol[lastIndex][1] = StocksPrice[i].volume
				                
				                if (lastIndex > 0) {
				                    var dealnum = Math.floor((StocksPrice[i].volume - nowVol[lastIndex-1][1])/100)
				                    if (price <= nowPrice[lastIndex-1][1]) {
				                        // upVol.push([x, [0, dealnum, 0, dealnum]])
				                        upVol[x] = [0, dealnum, 0, dealnum]
				                        upVol[i] = upVol[lastIndex]
				                    }else{
				                        // upVol.push([x, [dealnum, 0, 0, dealnum]])
				                        upVol[x] = [dealnum, 0, 0, dealnum]
				                        upVol[i] = upVol[lastIndex]
				                    }
				                }else{
				                    var dealnum = Math.floor(StocksPrice[i].volume/100)
				                    // upVol.push([x, [dealnum, 0, 0, dealnum]])
				                    upVol[x] = [dealnum, 0, 0, dealnum]
				                }
				                
				            }else{
				                nowPrice.push([x, price])
				                averagePrice.push([x, avg])

				                nowVol.push([x, StocksPrice[i].volume])
				                var dealnum = Math.floor((StocksPrice[i].volume - nowVol[lastIndex][1])/100)
				                if (price <= nowPrice[lastIndex][1]) {
				                    // upVol.push([x, [0, dealnum, 0, dealnum]])
				                    upVol[x] = [0, dealnum, 0, dealnum]
				                }else{
				                    // upVol.push([x, [dealnum, 0, 0, dealnum]])
				                    upVol[x] = [dealnum, 0, 0, dealnum]
				                }
				                
				            }
				        }else{
				            nowPrice.push([x, price])
				            averagePrice.push([x, avg])

				            nowVol.push([x, StocksPrice[i].volume])
				            var dealnum = Math.floor(StocksPrice[i].volume/100)
				            // upVol.push([x, [dealnum, 0, 0, dealnum]])
				            var ix = x - 1
				            while (ix >= 0) {
				            	upVol[ix] = [0,0,0,0]
				            	ix--
				            }
				            upVol[x] = [dealnum, 0, 0, dealnum]
				        }
				    }
				    while (upVol.length < 242) {
				    	upVol.push([0,0,0,0])
				    }
				    
					option1 = {
				        tooltip: {
				            trigger: 'axis',
				            axisPointer: {
				                type: 'cross'
				            },
				            formatter: null
				        },
				        axisPointer: {
				            link: {xAxisIndex: 'all'}
				        },
				        grid: [{
				            left: 50,
				            right: 50,
				            top: '5%',
				            height: '60%'
				        }, {
				            left: 50,
				            right: 50,
				            top: '72%',
				            height: '20%'
				        }],
				        dataZoom: [
							{
								type: 'inside'
							}
						],
				        xAxis : [
				            {
				                type : 'category',
				                boundaryGap : false,
				                axisLine: {onZero: true},
				                data: nowTime,
				                
				            },
				            {
				                gridIndex: 1,
				                type : 'category',
				                boundaryGap : false,
				                axisLine: {onZero: true},
				                data:nowTime,
				                axisTick: {show: false},
				                axisLabel: {show: false},
				            }
				       ],
				        yAxis : [
				            {
				                type : 'value',
				                min: priceMin,
				                max: priceMax
				            },
				            {
				                gridIndex: 1,
				                type : 'value',
				                axisLabel: {show: false},
				                splitNumber: 2
				            }
				        ],
				        series : [
				            {
				                name:'当前价格',
				                type:'line',
				                data:nowPrice,
				                xAxisIndex: 0,
				                yAxisIndex: 0,
				                hoverAnimation: false,
				                itemStyle: {
				                    color: '#01AAED'
				                },
				                markLine: {  
				                    silent: true,
				                    data: [{
				                        yAxis: parseFloat($("#mainOpen").text()),
				                        lineStyle: {
				                        	color: '#cc0033'
				                        }
				                    }]
				                },
				            },
				            {
				                name:'平均价格',
				                type:'line',
				                data:averagePrice,
				                xAxisIndex: 0,
				                yAxisIndex: 0,
				                hoverAnimation: false,
				                itemStyle: {
				                    color: '#2F4056'
				                }
				            },
				            {
				                name: '成交量',
				                type: 'candlestick',
				                xAxisIndex: 1,
				                yAxisIndex: 1,
				                data: upVol,
				                itemStyle:{
				                    normal:{
				                        color: 'green',
				                        color0: 'red',
				                        borderColor: null,
				                        borderColor0: null
				                    }
				                },
				                hoverAnimation: false,
				            },
				        ]
				    };
					var otherHeight = $("#mainTabbar").height() + 90 + $(".tab-content").children('.main-row').eq(0).height() + $(".tab-content").children('.main-row').eq(1).height()
					$("#echartsInstance").css({"width": $("#echartsInstance").parent().width(), "height": window.innerHeight - otherHeight})
					// 初始化图表
					var charts = echarts.init(document.getElementById('echartsInstance'))
					charts.clear()
					charts.setOption(option1)
				}else{
					callback()
				}
			}).error(function(){
				console.log('ajax error')
				if (typeof errorHandler === 'function')
					errorHandler()
			})
			
				

			
		}
	}

	// 刷新中间部分的数据
	var refreshMainData = function(t=false){
		if (App.selectedStock != '') {
			var selectedCode = document.getElementById("selectedCode")
			selectedCode.innerHTML = ''
			var scriptElem = document.createElement("script")
			scriptElem.src = "http://hq.sinajs.cn/list=sh" + App.selectedStock
			sinaScript.appendChild(scriptElem)
			scriptElem.onload = function(){
				// 刷新中间部分的数据
				var digits = eval("hq_str_sh" + App.selectedStock).split(',')
				// console.log(digits)
				$("#addBtnLabel").html(stockDb({id: App.selectedStock}).first().name + "(" + App.selectedStock + ")")
				

				var price = parseFloat(digits[3])
				var open = parseFloat(digits[1])

				// 涨跌的颜色class
				var updown = open == 0 ? '' : price>open?'up-label':price<open?'down-label':''
				// 涨跌图标
				var icon = open == 0 ? '--' : price>open?'▲':price<open?'▼':'--'

				var close = parseFloat(digits[2])
				var minus = Math.abs(price-open)
				$("#mainPrice").html(price.toFixed(2))
				$("#mainUpdown").html(icon)
				$("#mainUpdownPrice").html(minus.toFixed(2))
				$("#mainUpdownPercent").html((open == 0 ? 0 : minus/open*100).toFixed(2) + "%")
				$("#mainTime").html(digits[30] + " " + digits[31])
				// 去除所有涨跌颜色类，然后添加现在的涨跌类
				$("#mainPriceRow").removeClass("up-label")
				$("#mainPriceRow").removeClass("down-label")
				$("#mainPriceRow").addClass(updown)
				// $("#mainUpdown").removeClass("up-label")
				// $("#mainUpdown").removeClass("down-label")
				// $("#mainUpdown").addClass(updown)

				$("#mainOpen").html(open.toFixed(2))
				$("#mainMax").html(parseFloat(digits[4]).toFixed(2))
				$("#mainMin").html(parseFloat(digits[5]).toFixed(2))
				$("#mainClose").html(close.toFixed(2))
				// 成交量除以100之后单位是“手”
				$("#mainVol").html(Math.floor(parseInt(digits[8])/100) + "手")
				// 除以一万得到单位“万元”
				$("#mainTotal").html((parseFloat(digits[9])/10000).toFixed(2) + "万元")
				// 涨停=开盘*1.1，跌停=开盘*0.9
				$("#mainMaxStop").html((open*1.1).toFixed(2))
				$("#mainMinStop").html((close*0.9).toFixed(2))
				// 买卖颜色初始化
				$("#buyPrice").children().removeClass("up-label")
				$("#buyPrice").children().removeClass("down-label")
				$("#sellPrice").children().removeClass("up-label")
				$("#sellPrice").children().removeClass("down-label")
				for (var i = 0; i < 5; i++) {
					var buyPrice = parseFloat(digits[11+i*2]).toFixed(2)
					var sellPrice = parseFloat(digits[21+(4-i)*2]).toFixed(2)
					$("#buyPrice").children().eq(i).html(buyPrice)
					$("#buyVol").children().eq(i).html(Math.floor(digits[10+i*2]/100))
					$("#sellPrice").children().eq(i).html(sellPrice)
					$("#sellVol").children().eq(i).html(Math.floor(digits[20+(4-i)*2]/100))

					if (buyPrice > price) $("#buyPrice").children().eq(i).addClass("up-label")
					else if (buyPrice < price) $("#buyPrice").children().eq(i).addClass("down-label")

					if (sellPrice > price) $("#sellPrice").children().eq(i).addClass("up-label")
					else if (sellPrice < price) $("#sellPrice").children().eq(i).addClass("down-label")
				}

				if (!t) { // 不是从定时任务中调用，也就是用户手动点开时，执行下面的操作
					var buySell = $("#buySellTab .layui-tab-title .layui-this").index()
					$("#buySellPriceInput").val(parseFloat(digits[buySell == 0 ? 11:21]).toFixed(2)).change()

					// var buySell = $("#buySellTab .layui-tab-title .layui-this").index()
					
					if (buySell == 0) {
						var sPrice = parseFloat($("#buySellPriceInput").val())
						var sNum = parseInt($("#buySellVolInput").val())
						var userTotal = parseFloat($("#userHoldingTotal").text())
						$("#buySellHolding").text(((sPrice*sNum + userTotal)/App.userDefaultRemain*100).toFixed(1))
						$("#buySellAvailable").text(sPrice == 0 ? 0 : Math.floor(parseFloat($("#userRemainTotal").text())/sPrice/100)*100)
					}else{
						
						if (App.holding.hasOwnProperty('sh'+App.selectedStock)){
							// $("#buySellHolding").text((userTotal/App.userDefaultRemain*100).toFixed(1))
							var available = App.holding['sh'+App.selectedStock].available
							var degDb = TAFFY(App.userDelegate)
							var degQuery = degDb({stockId: 'sh'+App.selectedStock, type: false}).get()
							console.log(degQuery)
							for (var i=0; i < degQuery.length; i++){
								available -= degQuery[i].num
							}
							$("#buySellAvailable").text(available)
							// $("#buySellVolInput").val(available).change()
						}else{
							$("#buySellVolInput").val(0).change()
							$("#buySellAvailable").text(0)
							// $("#buySellHolding").text((userTotal/App.userDefaultRemain*100).toFixed(1))
						}
						
					}
					$("#addBtn").removeClass('layui-btn-disabled')
					if (App.userLogined){
						$.get('stock/check/sh'+App.selectedStock, function(data){
							if (data.status === 203){ // 已添加
								$("#addBtnIcon").html("&#xe658;")
								$("#addBtn").removeClass("addBtn")
								$("#addBtn").addClass("deleteBtn")
							}else{
								$("#addBtnIcon").html("&#xe600;")
								$("#addBtn").removeClass("deleteBtn")
								$("#addBtn").addClass("addBtn")
							}
						})
					}
					
				}
			}
			
		}
	}

	// 跳到标签页
	var selectMainTab = function(i){
		if (i < 0 || i >= App.selectingStock.length) {
			// 标签页全部都关了
			$(".tab-content").hide()
			App.selectedStock = ''
			return
		}
		$(".tab-content").show()
		// 高亮选中的标签
		$("#mainTabbar").children().removeClass("main-tabbar-select")
		$("#mainTabbar").children().eq(i).addClass("main-tabbar-select")
		// 刷新中间部分
		App.selectedStock = App.selectingStock[i].id
		refreshMainData()

		element.tabChange('digramTab', 'timeline')
		// element.tabChange('buySellTab', 'buy')
	}

	// 添加一个标签页
	var addMainTab = function(id, name){
		var shifting = false
		for (var i = 0; i < App.selectingStock.length; i++) {
			if (App.selectingStock[i].id == id){
				// 如果列表中已经存在，把它移到最前面
				App.selectingStock.unshift(App.selectingStock[i])
				App.selectingStock.splice(i+1, 1)
				console.log(App.selectingStock)
				shifting = true
			}
		}
		if (!shifting) {
			// 如果没有上述的存在，直接添加在最前面
			App.selectingStock.unshift({id: id, name: name})
		}
		// 模板引擎渲染标签
		layui.laytpl($("#mainTabTpl").html()).render(App.selectingStock, function(html){ 
			$("#mainTabbar").html(html)
			// 绑定点击切换标签页事件
			$(".main-tabbar-tab").unbind("click").bind("click", function(e){
				selectMainTab($(this).index())
			})
			// 绑定删除标签页事件
			$(".main-tabbar-close").unbind("click").bind("click", function(e){
				var index = $(this).parent().index()
				$(this).parent().remove()
				App.selectingStock.splice(index, 1)
				if ($(this).parent().hasClass("main-tabbar-select")) {
					// 切换到左边
					var jumpIndex = index - 1
					selectMainTab(jumpIndex < 0 ? 0 : jumpIndex)
				}

			})
		})
		// 切换
		selectMainTab(0)
	}

	// 添加自选股的按钮
	$("#addBtn").click(function(){
		// console.log($("#addBtnIcon").html())
		if ($("#addBtn").hasClass('layui-btn-disabled')) return
		if (!App.userLogined) {
			// jquery-ui 特效爆炸
			$("#body-login").css({backgroundColor: '#ffff00'})
			$("#body-login").animate({backgroundColor: ''}, 1000)
			return
		}
		if ($("#addBtn").hasClass('addBtn')){
			// console.log("add")
			$("#addBtn").addClass('layui-btn-disabled')
			$.get('stock/add/sh'+App.selectedStock, function(data){
				$("#addBtn").removeClass('layui-btn-disabled')
				if (data.status === -1){
					loginInvaildated()
					return
				}
				if (data.status === 200) {
					$("#addBtnIcon").html("&#xe658;")
					$("#addBtn").removeClass("addBtn")
					$("#addBtn").addClass("deleteBtn")

					if ($("#leftTab .layui-tab-title .layui-this").index() == 1) refreshSelectedStock()

					humane.log('已添加自选股')					
				}else{
					humane.log('系统出错，GG')
				}
			})
		}else if ($("#addBtn").hasClass('deleteBtn')){
			// console.log("delete")
			$("#addBtn").addClass('layui-btn-disabled')
			$.get('stock/delete/sh'+App.selectedStock, function(data){
				$("#addBtn").removeClass('layui-btn-disabled')
				if (data.status === -1){
					loginInvaildated()
					return
				}
				if (data.status === 200) {
					$("#addBtnIcon").html("&#xe600;")
					$("#addBtn").removeClass("deleteBtn")
					$("#addBtn").addClass("addBtn")

					if ($("#leftTab .layui-tab-title .layui-this").index() == 1) refreshSelectedStock()

					humane.log('已删除自选股')
				}else{
					humane.log('系统出错，GG')					
				}
			})
		}
	})


	//监听表格点击
	table.on('tool(stock)', function(obj){ //注：tool是工具条事件名，stock是table原始容器的属性 lay-filter="对应的值"
		// var data = obj.data; //获得当前行数据
		// var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		// var tr = obj.tr; //获得当前行 tr 的DOM对象

		if(obj.event === 'detail'){ //查看
			// 点击左边之后添加到标签页上
			addMainTab(obj.data.id, obj.data.name)
		}
	});

	// 日K图表
	var refreshKLine = function(index){
		if (index == 1 || index == 2) {
			var apiName = index == 2 ? 'week' : ''
			$.get('stock/'+apiName+'quote/sh' + App.selectedStock, function(data){
				console.log(data)
				var dayValues = []
				var kValues = []
				var ma5 = []
				var ma10 = []
				var vol = []
				var max = 0
				var min = 0

				for (var i = 0; i < data.data.length; i++) {
					var item = data.data[i]
					var kv = [item.open, item.close, item.min, item.max]
					kValues.push(kv)
					dayValues.push(item.time.split(" ")[0])

					var maxmax = Math.max.apply(null, kv)
					if (maxmax > max) {
						max = maxmax
					}

					var minmin = Math.min.apply(null, kv)
					if (min == 0) {
						min = minmin
					}else if (minmin < min) {
						min = minmin
					}

					if (i < 5) {
						ma5.push('-')
					}else{
						var sum = 0
						for (var j = 0; j < 5; j++) {
							sum += parseFloat(data.data[i-j].close)
						}
						ma5.push((sum/5).toFixed(3))
					}
					if (i < 10) {
						ma10.push('-')
					}else{
						var sum = 0
						for (var j = 0; j < 10; j++) {
							sum += parseFloat(data.data[i-j].close)
						}
						ma10.push((sum/10).toFixed(3))
					}


					if (item.open > item.close) {
						vol.push([item.volume, 0, 0, item.volume])
						// vol.push([i, item.volume, 1])
					}else{
						vol.push([0, item.volume, 0, item.volume])
						// vol.push([i, item.volume, -1])
					}
					

				}

				// console.log(ma5)

				option2 = {
			        tooltip: {
			            trigger: 'axis',
			            axisPointer: {
			                type: 'cross'
			            },
			            formatter: function(params, ticket, callback){
			            	// console.log(params)
			            	return  params[0].axisValue + "<br>" + 
			            			params[0].marker + "开盘: " + params[0].data[1] + "<br>" +
			            			params[0].marker + "收盘: " + params[0].data[2] + "<br>" +
			            			params[0].marker + "最高: " + params[0].data[4] + "<br>" +
			            			params[0].marker + "最低: " + params[0].data[3] + "<br>" +
			            			params[1].marker + "MA5: " + params[1].data + "<br>" +
			            			params[2].marker + "MA10: " + params[2].data + "<br>" +
			            			params[3].marker + "成交量: " + params[3].data[4] + "<br>"
			            }
			        },
			        axisPointer: {
			            link: {xAxisIndex: 'all'}
			        },
			        grid: [{
			            left: 50,
			            right: 50,
			            top: '5%',
			            height: '60%'
			        }, {
			            left: 50,
			            right: 50,
			            top: '72%',
			            height: '20%'
			        }],
			        // visualMap: {
			        //     show: false,
			        //     seriesIndex: 3,
			        //     dimension: 2,
			        //     pieces: [{
			        //         value: 1,
			        //         color: 'green'
			        //     }, {
			        //         value: -1,
			        //         color: 'red'
			        //     }]
			        // },
			        dataZoom: [
			        	{
			        		type: 'inside'
			        	}
			        ],
			        xAxis : [
			            {
			                type : 'category',
			                boundaryGap : false,
			                axisLine: {onZero: true},
			                data: dayValues,
			                
			            },
			            {
			                gridIndex: 1,
			                type : 'category',
			                boundaryGap : false,
			                axisLine: {onZero: true},
			                data:dayValues,
			                axisTick: {show: false},
			                axisLabel: {show: false},
			            }
			        ],
			        yAxis : [
			            {
			                type : 'value',
			                min: min,
			                max: max
			            },
			            {
			                gridIndex: 1,
			                type : 'value',
			                axisLabel: {show: false},
			                splitNumber: 2
			            }
			        ],
			        series : [
			            {
			                name:'日K',
			                type:'candlestick',
			                data:kValues,
			                xAxisIndex: 0,
			                yAxisIndex: 0,
			                hoverAnimation: false,
			                // itemStyle: {
			                //     color: '#01AAED'
			                // }
			                itemStyle:{
			                    normal:{
			                        color: 'green',
			                        color0: 'red',
			                        borderColor: null,
			                        borderColor0: null
			                    }
			                },
			            },
			            {
			                name:'MA5',
			                type:'line',
			                data:ma5,
			                xAxisIndex: 0,
			                yAxisIndex: 0,
			                hoverAnimation: false,
			                // itemStyle: {
			                //     color: '#2F4056'
			                // }
			            },
						{
			                name:'MA10',
			                type:'line',
			                data:ma10,
			                xAxisIndex: 0,
			                yAxisIndex: 0,
			                hoverAnimation: false,
			                // itemStyle: {
			                //     color: '#2F4056'
			                // }
			            },
			            {
			                name: '成交量',
			                type: 'candlestick',
			                xAxisIndex: 1,
			                yAxisIndex: 1,
			                data: vol,
			                itemStyle:{
			                    normal:{
			                        color: 'green',
			                        color0: 'red',
			                        borderColor: null,
			                        borderColor0: null
			                    }
			                },
			                hoverAnimation: false,
			            },
			        ]
			    };
				var otherHeight = $("#mainTabbar").height() + 90 + $(".tab-content").children('.main-row').eq(0).height() + $(".tab-content").children('.main-row').eq(1).height()
					$("#echartsInstance").css({"width": $("#echartsInstance").parent().width(), "height": window.innerHeight - otherHeight})
				// 初始化图表
				var charts = echarts.init(document.getElementById('echartsInstance'))
				charts.clear()
				charts.setOption(option2)
			})
			

		}
	}

	// 监听标签页切换
	element.on('tab(digramTab)', function(data){
		console.log(data)
		App.digramTabIndex = data.index
		if (data.index == 0) {
			var now = new Date()
			var dateFormat = function(now){return now.getFullYear()+'-'+(now.getMonth()<9?'0':'')+(now.getMonth()+1)+'-'+(now.getDate()<10?'0':'')+now.getDate()}
			var callback = function(){
				now.setDate(now.getDate() - 1)
				refreshTimeline(dateFormat(now), callback)
			}
			var errorHandler = function(){
				console.log('errorHandler')
				refreshTimeline(dateFormat(now), callback)
			}
			// console.log(typeof errorHandler)
			refreshTimeline(dateFormat(now), callback, errorHandler)
			// refreshTimeline(dateFormat(now), callback)
		}else{
			refreshKLine(data.index)
		}
	})

	// 交易窗口
	
	// 买卖切换
	element.on('tab(buySellTab)', function(data){
		console.log(data)
		$("#buySellSubmit").removeClass("buyButton")
		$("#buySellSubmit").removeClass("sellButton")
		$("#buySellSubmit").addClass(data.index == 0 ? "buyButton":"sellButton")
		$("#buySellSubmit").text(data.index == 0 ? "买入":"卖出")
		console.log("#"+(data.index==0?"buy":"sell")+"Price")
		$("#buySellPriceInput").val(parseFloat($("#"+(data.index==0?"buy":"sell")+"Price").children().eq(data.index==0?0:4).text()).toFixed(2)).change()
		$(".buySellLabel").text(data.index == 0 ? "买":"卖")

		if (data.index == 0) {
			var sPrice = parseFloat($("#buySellPriceInput").val())
			var sNum = parseInt($("#buySellVolInput").val())
			var userTotal = parseFloat($("#userHoldingTotal").text())
			$("#buySellHolding").text(((sPrice*sNum + userTotal)/App.userDefaultRemain*100).toFixed(1))
			$("#buySellAvailable").text(sPrice == 0 ? 0 : Math.floor(parseFloat($("#userRemainTotal").text())/sPrice/100)*100)
		}else{
			if (App.holding.hasOwnProperty('sh'+App.selectedStock)){
				// $("#buySellHolding").text((userTotal/App.userDefaultRemain*100).toFixed(1))
				var available = App.holding['sh'+App.selectedStock].available
				var degDb = TAFFY(App.userDelegate)
				var degQuery = degDb({stockId: 'sh'+App.selectedStock, type: false}).get()
				for (var i=0; i < degQuery.length; i++){
					available -= degQuery[i].num
				}
				$("#buySellAvailable").text(available)
				// $("#buySellVolInput").val(available).change()
			}else{
				$("#buySellVolInput").val(0).change()
				$("#buySellAvailable").text(0)
				// $("#buySellHolding").text((userTotal/App.userDefaultRemain*100).toFixed(1))
			}
		}
	})

    //* 价格、量控制器
    $("#buySellPriceInput,#buySellVolInput").on('change', function(e){
    	var price = parseFloat($("#buySellPriceInput").val())
    	var vol = parseInt($("#buySellVolInput").val())
    	var total = price*vol
    	if(total<0) total=0
    	if(total == 0) $("#buySellTotal").css('color', 'inherit')
    	else $("#buySellTotal").css('color', '#FF5722')
    	$("#buySellTotal").html(total.toFixed(2))
		var userTotal = parseFloat($("#userHoldingTotal").text())
		$("#buySellHolding").text(((userTotal + total)/App.userDefaultRemain*100).toFixed(1))
    })
    $("#buySellPriceInput").blur(function(){
    	var priceInput = $("#buySellPriceInput").val()
    	var price = parseFloat(priceInput)
    	if (isNaN(price)) {
    		price = 0	
    	}
    	if (price < 0) {
    		price = 0
    	}
    	$("#buySellPriceInput").val(price.toFixed(2))
    })

    $("#buySellVolInput").blur(function(){
    	var volInput = $("#buySellVolInput").val()
    	var vol = parseInt(volInput)
    	if (isNaN(vol)) {
    		vol = 0
    	}
    	if (vol < 0) {
    		vol = 0
    	}
		var available = parseInt($("#buySellAvailable").text())
		if (vol > available) {
			vol = available
		}
    	$("#buySellVolInput").val(vol).change()
    })

    $("#buySellPriceAdd").click(function(){
    	$("#buySellPriceInput").val((parseFloat($("#buySellPriceInput").val())+0.01).toFixed(2)).change()
    })
    $("#buySellPriceReduce").click(function(){
    	var price = parseFloat($("#buySellPriceInput").val())
    	$("#buySellPriceInput").val((price<=0?0:price-0.01).toFixed(2)).change()
    })

    $("#buySellVolAdd").click(function(){
		var available = parseInt($("#buySellAvailable").text())
		var vol = parseInt($("#buySellVolInput").val()) + 100
		if (vol > available) vol -= 100
    	$("#buySellVolInput").val(vol).change()
    })
    $("#buySellVolReduce").click(function(){
    	var vol = parseInt($("#buySellVolInput").val())
    	$("#buySellVolInput").val(vol<=100?0:vol-100).change()
    })

    $("#buySellVolBtnGroup").children().click(function(e){
    	var idx = $(e.target).index()

		var holding = 1/(idx+1)
		var price = parseFloat($("#buySellPriceInput").val())
		$("#buySellVolInput").val(price == 0 ? 0 : Math.floor(parseFloat($("#userRemainTotal").text())*holding/price/100)*100).change()
		
    })

	// 买入或卖出按钮点击
    $("#buySellSubmit").click(function(){
		if ($(this).hasClass('layui-btn-disabled')) return
		if (!App.userLogined) {
			// jquery-ui 特效爆炸
			$("#body-login").css({backgroundColor: '#ffff00'})
			$("#body-login").animate({backgroundColor: ''}, 1000)
			return
		}

    	var buySell = $("#buySellTab .layui-tab-title .layui-this").index()
    	var total = parseFloat($("#buySellTotal").text())

    	if (isNaN(total) || total <= 0){
    		wiggleEffect($("#buySellTotal"))
    		return
    	}
		if (parseInt($("#buySellAvailable").text()) < parseInt($("#buySellVolInput").val())) {
			wiggleEffect($("#buySellAvailable"))
			return
		}


		// 提交委托请求
		$("#buySellSubmit").removeClass('layui-btn-primary')
		$("#buySellSubmit").addClass('layui-btn-disabled')
		$.ajax({
			type: 'post',
			url: 'delegate/add',
			data: JSON.stringify({
				stockId: 'sh'+App.selectedStock,
				price: parseFloat($("#buySellPriceInput").val()),
				num: parseInt($("#buySellVolInput").val()),
				type: buySell == 0 ? true : false
			}),
			contentType: "application/json; charset=utf-8",  
            dataType: "json",
			success: function(result){
				$("#buySellSubmit").addClass('layui-btn-primary')
				$("#buySellSubmit").removeClass('layui-btn-disabled')
				if (result.status == -1){
					loginInvaildated()
					return
				}
				if(result.status === 200){
					// 刷新委托表数据
					// refreshDelegate()
					// showDelegate()
					$("#buySellVolInput").val(0).change()
					element.tabChange('userTab', 'delegate')
					humane.log('已委托'+(buySell == 0 ? '买入' : '卖出'))
				}else{
					// "org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'userId' not found. Available parameters are [param5, param6, user_id, price, num, time, param3, type, stock_id, param4, param1, param2]nested exception is org.apache.ibatis.binding.BindingException: Parameter 'userId' not found. Available parameters are [param5, param6, user_id, price, num, time, param3, type, stock_id, param4, param1, param2]"
					humane.log('系统出错，GG')
					console.log(result)
				}
			}
		})
		

    })

	// 特效爆炸
	var wiggleEffect = function(obj){
		// console.log(obj)
		obj.css('color', '#FF5722')
		obj.animate({marginLeft: '+=8px'}, 100, function(){
			obj.animate({marginLeft: '-=8px'}, 100, function(){
				obj.animate({marginLeft: '+=8px'}, 100, function(){
					obj.animate({marginLeft: '-=8px'}, 100, function(){
						obj.css('color', 'inherit')
					})
				})
			})
		})
	}

	// 右侧用户区域

	element.on('tab(userTab)', function(data){
		$("#userDataContainer").html('')
		var idx = data.index
		console.log(idx)
		switch (idx){
			case 0:
				refreshHolding()
				break
			case 1: 
				refreshDelegate()
				// showDelegate()
				break
			case 2:
				refreshDeal()
				break
			default:
				break
		}
	})

	// 刷新持仓
	var refreshHolding = function(){
		$.get('deal/holding', function(result){
			if (result.status === -1) {
				// alert('会话过期，重新登陆')
				loginInvaildated()
				return
			}
			// console.log(result)
			// var data = result.data.holding
			// var list = []
			// App.holding.splice(0, App.holding.length) // 清空
			if (result.status != 200) return
			App.holding = result.data.holding
			// 	//  可用持仓未计算
			// 	//  问题待解：没有持仓数据的时候盈亏也不是为零
			// 	var item = data[stockid]
			// 	var stock_id = stockid.replace('sh', '')
			// 	var name = stockDb({id: stock_id}).first().name
			
			$("#userRemainTotal").text((App.userDefaultRemain-result.data.total).toFixed(2))
			
			
			holdingPrice()
			refreshMainData()
		})
	}

	// 持仓列表刷新价格
	var holdingPrice = function(){
		if (!$.isEmptyObject(App.holding)) {
			var stockids = ''
			for (var stockid in App.holding){
				if (App.holding.hasOwnProperty(stockid)) {
					// stockids.push(stockids)
					stockids += stockid + ','
				}
			}
			// console.log(App.holding)
			// console.log(stockids)
			// var stockids = App.holding.map(function(x){return 'sh'+x.stock_id})

			var holdingScript = document.getElementById("holdingScript")
			holdingScript.innerHTML = ''
			var scriptElem = document.createElement("script")
			scriptElem.src = "http://hq.sinajs.cn/list="+stockids
			holdingScript.appendChild(scriptElem)
			scriptElem.onload = function(){

				var total = 0
				var updown = 0
				var holdingTpl = []
				for (var stockid in App.holding){
					if (App.holding.hasOwnProperty(stockid)) {
						// stockids.push(stockids)
						var otem = App.holding[stockid]
						var stock_id = stockid.replace('sh', '')
						var item = {
							stock_id: stock_id,
							name: stockDb({id: stock_id}).first().name,
							buyPrice: otem.price,
							amount: otem.num,
							available: otem.available
						}
						
						var digits = eval("hq_str_sh" + stock_id).split(',')
						var price = parseFloat(digits[3])
						item.nowPrice = price.toFixed(2)
						var buyPrice = parseFloat(item.buyPrice)
						item.updown = price == 0 ? '--' : price>buyPrice?'▲':price<buyPrice?'▼':'--'
						item.updownClass = price == 0 ? '' : price>buyPrice?'up-label':price<buyPrice?'down-label':''
						item.volume = (price*item.amount/App.userDefaultRemain*100).toFixed(1)
						item.updownPrice = (price-buyPrice).toFixed(2)
						item.updownRate = ((price-buyPrice)/buyPrice*100).toFixed(3)
						holdingTpl.push(item)
						total += price*item.amount
						updown += (price-buyPrice)*item.amount
					}
				}

				$("#userHoldingTotal").text(total.toFixed(2))
				$("#userVolume").text((total/App.userDefaultRemain*100).toFixed(1))
				
				$("#userUpdown").text(updown.toFixed(2))
				$("#userUpdown").removeClass("up-label")
				$("#userUpdown").removeClass("down-label")
				$("#userUpdown").addClass(updown == 0 ? "" : updown>0?"up-label":"down-label")
				
				var userIdx = $("#userTab .layui-tab-title .layui-this").index()
				if (userIdx == 0) {
					layui.laytpl($("#holdingTpl").html()).render(holdingTpl, function(html){
						$("#userDataContainer").html(html)
					})
				}
				

			}
		}
		
	}

	// 刷新委托
	var refreshDelegate = function(callback=null){
		$.get('delegate/list', function(result){
			if (result.status === -1) {
				// alert('会话过期，重新登陆')
				loginInvaildated()
				return
			}

			App.userDelegate = result.data.map(function(item){
				item.name = stockDb({id: item.stockId.replace('sh','')}).first().name
				return item
			})

			if ($("#userTab .layui-tab-title .layui-this").index() == 1) {
				layui.laytpl($("#delegateTpl").html()).render(App.userDelegate, function(html){
					$("#userDataContainer").html(html)
				})
			}

			if (callback != null) {
				callback()
			}
		})
	}

	// 刷新成交记录
	var refreshDeal = function(){
		App.dealPage = 1
		// App.dealHistory = []
		getUserDeal(App.dealPage)
	}

	// 分页查询成交记录
	var getUserDeal = function(page=1){
		if (page != 0){
			$.get('deal/history?page='+page, function(result){
				if (result.status == -1){
					loginInvaildated()
					return
				}
				if (Array.isArray(result.data)) {
					// App.dealHistory.concat(result.data)
					var dealData = result.data.map(function(item){
						item.name = stockDb({id: item.stockId.replace('sh','')}).first().name
						return item
					})
					layui.laytpl($("#dealTpl").html()).render(dealData, function(html){
						$("#userDataContainer").append(html)
					})
					
					if (result.data.length < 10) {
						App.dealPage = -1
					}else{
						App.dealPage = page
					}
				}
				
			})
		}
	}

	// 点击持仓信息刷新中间部分
	$("#userDataContainer").on('click', '.holdingRow', function(){
		var stock_id = $(this).find(".holdingRowStockid").first().text()
		var name = $(this).find(".holdingRowName").first().text()
		// console.log(stock_id)
		addMainTab(stock_id, name)
	})
	// 点击股票信息刷新中间部分
	$("#userDataContainer").on('click', '.delegateStock', function(){
		var stock_id = $(this).find(".delegateRowStockid").first().text()
		var name = $(this).find(".delegateRowName").first().text()
		// console.log(stock_id)
		addMainTab(stock_id, name)
	})
	// 委托取消按钮点击
	$("#userDataContainer").on('click', '.delegateCancel', function(){
		if ($(this).hasClass('layui-btn-disabled')) return
		$(this).removeClass('layui-btn-danger')
		$(this).addClass('layui-btn-disabled')
		var idx = $(this).parent().parent().index()
		// console.log(idx)
		var delegateId = App.userDelegate[idx].id
		console.log(delegateId)
		$.get('delegate/cancel?delegateId='+delegateId, function(result){
			if (result.status === -1) {
				loginInvaildated()
				return
			}
			if (result.status === 200) {
				humane.log('委托已取消')
				refreshDelegate()
			}else{
				humane.log('系统出错，GG')
			}
		})
	})

	// 防止表单提交刷新页面
	var form = layui.form;
    form.on('submit(loginForm)', function(data){
        return false;
    });
    //* 登录<->注册
    //.post(url,data,function())
    $("#user").blur(function(){
        var username = $("#user").val()
        
        if(username == ""){
            $("#regist-message").html("请输入用户名")
        }
        else{
        	if(App.loginRegState == 0){

	        }
	        else{
	            $("#regist-message").html("")
	            $.ajax({  
	                type: "get",  
	                url: "user/check/"+username,  
	                success: function(result) {  
	                    if(result.status === 200){
	                        $("#regist-message").html("")
	                    }else{
	                        // regist failed
	                        $("#regist-message").html(result.message)
	                    }  
	                }
	            });
	        }  
        }             
    })

    $("#loginBtn").click(function(){
    	if ($("#loginBtn").hasClass("layui-btn-disabled")) return
    	$("#login-message").html("")
    	$("#regist-message").html("")
        var username = $("#user").val()
        var password = $("#password").val()//登录
        if(App.loginRegState == 0 )
        {
            if(username == ""){
                $("#regist-message").html("请输入用户名")
                return
            }
            if (password == "") {
            	$("#regist-message").html("请输入密码")
                return
            }
            
        	$("#loginBtn").addClass("layui-btn-disabled")

    		$.ajax({  
                type: "post",  
                url: 'user/login',  
                data: JSON.stringify({
                    username: username,
                    password: password
                }), 
                contentType: "application/json; charset=utf-8",  
                dataType: "json",  
                success: function(result) {  
                    console.log(result)
                    $("#loginBtn").removeClass("layui-btn-disabled")
                    if(result.status === 200){
                        // login success
                        $("#body-login").toggle()
                        $("#body-user").fadeToggle(1000)
                        $("#user-name").html($("#user").val())
						loginSuccess()
                    }else{
                        // login failed
                        $("#login-message").html(result.message)
                    }  
                }
            });
            
            
        }
        //* 注册
        else{    
            //判断用户名是否被注册
            var username = $("#user").val()
            var password1 = $("#password").val()
            var password2 = $("#confirm-password").val()
            if(password1 ==""||password2 ==""){
                $("#regist-message").html("请输入密码")
            }
            else{

                if(password1 == password2){
                    // regist()
                    $("#loginBtn").addClass("layui-btn-disabled")
                	$.ajax({  
		                type: "post",  
		                url: 'user/regist',  
		                data: JSON.stringify({
		                    username: username,
		                    password: password
		                }), 
		                contentType: "application/json; charset=utf-8",  
		                dataType: "json",  
		                success: function(result) {  
		                	$("#loginBtn").removeClass("layui-btn-disabled")
		                	if (result.status === 200) {
		                		$("#body-login").toggle()
	                            $("#body-user").fadeToggle(1000)
	                            $("#user-name").html($("#user").val())
								loginSuccess()
		                	}else{
		                		$("#login-message").html(result.message)
		                	}
		                }
		            });
                    
                }
                else{
                    $("#regist-message").html("两次输入的密码不一致")
                }
            } 
        }
    })
    
    //* 去登录<->去注册
    // var selector = 0
    $("#toLoginBtn").click(function(){
        if(App.loginRegState == 0)
        {
            $("#loginBtn").html("注册")
            $("#toLoginBtn").html("去登录")
            $("#user").val(undefined)
            $("#password").val(undefined)
            
            $("#login-message").html("")
            App.loginRegState = 1
        }else{
            $("#loginBtn").html("登录")
            $("#toLoginBtn").html("去注册")
            $("#confirm-password").val(undefined)
            $("#regist-message").html("")
            App.loginRegState = 0
        }

        $("#title-login").toggle()
        $("#title-regist").toggle()
        $("#confirm-password").toggle()
        $("#login-Btn").css("margin-top","15px")
    })

    //* 注销
    $("#logoutBtn").click(function(){
        $.ajax({  
            type: "get",  
            url: 'user/outLogin', 
            success: function(result) {  
                console.log(result)
                if(result.status === 200){
                    // logout success
					logoutChangeUI()
                }
            }
        });
    })
    

    // 判断是否已登录 放在代码最后 定时器之前
    $.get("user/loginCheck", function(loginstatus){
    	console.log(loginstatus)
    	if(loginstatus.status === 200){
            // login success   
			$("#body-login").hide()
			$("#body-user").show() 
			$("#user-name").html(loginstatus.data)
            loginSuccess()
			
        }else{
            // login failed
			logoutChangeUI()
        }
    })

	// 登陆成功后做的事情
	var loginSuccess = function(){
		App.userLogined = true
		
		// 加载持仓 放在登陆之后
		$("#userDataContainer").css('height', window.innerHeight - 300)
		
		element.tabChange('userTab', 'holding')
		refreshDelegate()

		if ($("#leftTab .layui-tab-title .layui-this").index() == 1){
			refreshSelectedStock()
		}
	}

	// 登陆失效后做的事情
	var loginInvaildated = function(){
		humane.log('登陆会话已失效，请重新登陆')
		logoutChangeUI()
	}

	var logoutChangeUI = function(){
		App.userLogined = false
		$("#body-login").show()
		$("#body-user").hide()

		// 密码清空
		$("#password").val('')
		
		// 错误提示信息情况
		$("#regist-message").html("")
		$("#login-message").html("")

		// 登陆按钮解禁
		$("#loginBtn").removeClass("layui-btn-disabled")
		
		// 收藏按钮还原
		$("#addBtnIcon").html('&#xe600;')
		$("#addBtn").addClass('addBtn')
		$("#addBtn").removeClass('deleteBtn')

		// 自选股列表清空
		if ($("#leftTab .layui-tab-title .layui-this").index() == 1){
			table.reload("stockTable", {
				data: [],
				text: {
					none: '请先登录'
				},
				page: {
					curr: 1
				}
			})
		}

		// 仓位、可买/卖还原
		$("#buySellVolInput").val(0).change()
		$("#buySellHolding").text('0.0')
		$("#buySellAvailable").text('0')
	}

	// 成交记录滚动到底载入下一页
	$("#userDataContainer").on('scroll', function(e){
		// console.log(e)
		// console.log($("#userDataContainer").children().first().offset())
		if ($("#userTab .layui-tab-title .layui-this").index() == 2) {
			var nDivHight = $("#userDataContainer").height();
			nScrollHight = $(this)[0].scrollHeight;
			nScrollTop = $(this)[0].scrollTop;
			var paddingBottom = parseInt($(this).css('padding-bottom')),paddingTop = parseInt($(this).css('padding-top'));
			if(nScrollTop + paddingBottom + paddingTop + nDivHight >= nScrollHight){
				// console.log("bottom")
				getUserDeal(App.dealPage + 1)
			}
		}
		
	})

	$("#echartsInstance").css({"width": $("#echartsInstance").parent().width(), "height": window.innerHeight - ($("#mainTabbar").height() + 90 + $(".tab-content").children('.main-row').eq(0).height() + $(".tab-content").children('.main-row').eq(1).height())})

    // 测试用代码，上线前请删
    // $("#body-login").hide()
    // $("#body-user").show()

    // 定时器 放在代码最后
	setInterval(function(){
		// 判断是否是开盘时间
		var now = new Date()
		if (now.getDay() > 0 && now.getDay() < 6) {
			switch(now.getHours()){
				case 9:
					if (now.getMinutes() < 30) return
					break
				case 10:
					break
				case 11:
					if (now.getMinutes() > 30) return
				case 13:
					break
				case 14:
					break
				default:
					return
			}
		}else{
			return
		}
		if (App.getPriceTimerReady && !App.searching) {
			// 开始刷新
			sinaScript.innerHTML = ''
			var scriptElem = document.createElement("script")
			scriptElem.src = "http://hq.sinajs.cn/list=" + App.stockCodesInPage.join(',')
			sinaScript.appendChild(scriptElem)
			scriptElem.onload = function(){
				var idx = $("#leftTab .layui-tab-title .layui-this").index()
				if (idx == 0){
					for (var i = (App.stockTableCurr-1)*App.stockTableLimit; i < App.stockTableCurr*App.stockTableLimit; i++) {
						if (StockList[i] === undefined) break
						var digits = eval("hq_str_sh" + StockList[i].id).split(',')
						// var updown = digits[3]>digits[1]?'up-label':digits[3]<digits[1]?'down-label':''
						// var icon = digits[3]>digits[1]?'▲':digits[3]<digits[1]?'▼':'■'
						
						var price = parseFloat(digits[3])
						var open = parseFloat(digits[1])
						// 涨跌的颜色class
						var updown = open == 0 ? '' : price>open?'up-label':price<open?'down-label':''
						// 涨跌图标
						var icon = open == 0 ? '--' : price>open?'▲':price<open?'▼':'--'
						// var price = parseFloat(digits[3]).toFixed(2)
						StockList[i].price = '<span class="price-label '+updown+'">' + icon+'&nbsp;'+ (price < 10 ? '&nbsp;&nbsp;' : '') + price.toFixed(2) + '</span>'
					}
					table.reload('stockTable', {
						data: StockList
					})
				}else if (idx == 1 && App.userLogined){
					// TOTE 自选股列表的价格刷新
					
					table.reload('stockTable', {
						data: App.stockCodesInPage.map(function(item){
							var digits = eval("hq_str_sh" + StockList[i].id).split(',')
							var price = parseFloat(digits[3])
							var open = parseFloat(digits[1])
							// 涨跌的颜色class
							var updown = open == 0 ? '' : price>open?'up-label':price<open?'down-label':''
							// 涨跌图标
							var icon = open == 0 ? '--' : price>open?'▲':price<open?'▼':'--'
							// var price = parseFloat(digits[3]).toFixed(2)
							var priceSpan = '<span class="price-label '+updown+'">' + icon+'&nbsp;'+ (price < 10 ? '&nbsp;&nbsp;' : '') + price.toFixed(2) + '</span>'
							return {
								id: item.replace('sh', ''),
								name: stockDb({id: item.replace('sh', '')}).first().name,
								price: priceSpan
							}
						})
					})
				}
				
				// App.getPriceTimerReady = true
			}
		}

		// 刷新中间部分
		refreshMainData(true)

		// 一分钟刷新数据
		if (App.nowMinute != now.getMinutes() && now.getSeconds() > 10 && App.digramTabIndex == 0) {
			console.log("min refresh")
			App.nowMinute = now.getMinutes()
			var dateFormat = function(now){return now.getFullYear()+'-'+(now.getMonth()<10?'0':'')+(now.getMonth()+1)+'-'+(now.getDate()<10?'0':'')+now.getDate()}

			var callback = function(){
				now.setDate(now.getDate() - 1)
				refreshTimeline(dateFormat(now), callback)
			}

			// var errorHandler = function(){
			// 	refreshTimeline(dateFormat(now), callback)
			// }
			// console.log(typeof errorHandler)
			refreshTimeline(dateFormat(now), callback)
		}

		if (App.userLogined){
			// 刷新持仓部分的价格数据
			holdingPrice()

			// 刷新委托
			var delegateWorking = false
			for (var deg in App.userDelegate){
				if (deg.num < deg.deal) {
					// 有未完成的委托
					delegateWorking = true
					break
				}
			}

			if (delegateWorking) {
				var oldDelegate = App.userDelegate
				var oldDelegateDB = TAFFY(oldDelegate)
				refreshDelegate(function(){
					var delegateChange = []
					for (var deg in App.userDelegate){
						var oldDeal = oldDelegateDB({id: deg.id}).first().deal
						if (oldDeal != deg.deal){
							// 委托有变化
							delegateChange.push(stockDb({id: deg.id}).first().name +'('+ deg.id +')以'+ deg.price.toFixed(2) +'成交'+ (deg.deal-oldDeal) +'股')
							break
						}
					}
					if (delegateChange.length != 0) {
						humane.log(delegateChange)
						refreshHolding()
					}
				})
				
				
			}
		}
		

	}, 5000)

});
</script>

</body>
</html>